<template>
  <el-card class="box-card">
    <el-form ref="queryForm" :model="query" :inline="true">
      <el-form-item label="">
        <el-input v-model.trim="query.conditions.nickname" placeholder="昵称/医院/学校" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 160px;"
          v-model="query.conditions.provinceId"
          placeholder="全国"
          @change="getProOrCityList">
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 160px;" v-model="query.conditions.cityId" placeholder="全部城市">
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 100px;" v-model="query.conditions.type" placeholder="全部职业">
          <el-option label="医生" :value="1"></el-option>
          <el-option label="学生" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 120px;" v-model="query.conditions.tagidList" placeholder="全部标签">
          <el-option
            v-for="item in signList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button v-has-permi="['/wx/export/exportWxFansUserList']" type="primary" @click="exportFans()">导出EXECL</el-button>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <el-table v-loading="listLoading" :data="dataList" stripe border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="unionid" align="center" prop="unionid" width="220px" />
        <el-table-column label="昵称" align="center" prop="nickname" />
        <el-table-column label="职业" align="center" prop="type" />
        <el-table-column label="医院或学校" align="center">
          <template slot-scope="{row}">
            <span>{{ row.school || row.hospital }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="tagName" />
        <el-table-column label="注册时间" align="center" prop="createTime">
          <template slot-scope="{row}">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-has-permi="['/wx/menu/postUpdateWxFansUser']" type="text" @click="makeTag(2, row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize" @pagination="handleQuery" />
    </el-card>
    <!-- 打标签/编辑 -->
    <el-dialog :title="(formModel.id?'编辑粉丝信息':'打标签')" :visible.sync="formVisible" width="600px" append-to-body>
      <el-form ref="formModel" :model="formModel" :rules="formModelRules" label-width="150px">
        <el-form-item v-if="type===2" label="昵称:" prop="nickname">
          <el-input v-model.trim="formModel.nickname" clearable placeholder="请输入菜单名称" maxlength="12" />
        </el-form-item>
        <el-form-item label="标签名称" prop="tagidList">
          <el-select style="width: 120px;" v-model="formModel.tagidList" placeholder="请选择">
            <el-option
              v-for="item in signList"
              v-show="item.id!==1"
              :key="item.id"
              :label="item.tagName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { getFansList, getCityList, postUpdateWxFansUser, bindTag, delTag, exportWxFansUserList } from '@/api/wechatService/fans'
import { signListPage } from '@/api/wechatService/sign'
import { downloadFile } from '@/utils/tools'

export default {
  name: "index",
  data () {
    return {
      total: 0,
      provinceList: [],
      cityList: [],
      // 列表数据
      query: {
        pageNum: 1,
        pageSize: 10,
        conditions: {}
      },
      dataList: [],
      signList: [],
      listLoading: false,
      // 新增/编辑用户
      type: 1,
      formVisible: false,
      submitLoading: false,
      formModel: {},
      formModelRules: {
        nickname: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        tagidList: [
          { required: true, message: "请选择标签", trigger: "blur" }
        ]
      },
      multipleSelection: []
    }
  },
  mounted () {
    this.handleQuery()
    this.querySignList()
    this.getProOrCityList()
  },
  methods: {
    // 打标签
    makeTag(type, row) {
      this.type = type
      if (!this.multipleSelection.length&&type!==2) {
        this.$message.warning('请先选择粉丝用户')
        return
      }
      this.reset()
      if (type===2) {
        const { id, nickname, tagId } = row
        this.formModel = {
          id, nickname, tagidList: tagId
        }
      }
      this.formVisible = !this.formVisible
    },
    // 删除标签
    delTag() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先选择粉丝用户')
        return
      }
      this.$confirm(`请确认是否要删除选中人所关联的标签?`, { type: 'warning' }).then(() => {
        delTag({
          idList: this.multipleSelection
        }).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      })
    },
    // 导出
    async exportFans() {
      try {
        const params = {...this.query}
        if (this.multipleSelection) {
          params.conditions.idList = this.multipleSelection
        }
        delete params.pageNum
        delete params.pageSize
        const { data, headers } = await exportWxFansUserList(params)
        downloadFile(data, headers['content-type'], headers['content-disposition']?.split('filename=')[1])
      } catch (error) {
        console.log(error)
      }
    },
    // 查询标签list
    querySignList() {
      signListPage({
        pageSize: 1000,
        pageNum: 1
      }).then(res => {
        this.signList = res.data.records
      })
    },
    // 省份/城市
    getProOrCityList(id = 0) {
      getCityList({ id }).then(res => {
        if (id!==0) {
          this.cityList = res.data
          this.$set(this.query.conditions, 'cityId', '')
        } else {
          this.provinceList = res.data
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(o => o.id);
    },
    handleQuery () {
      this.listLoading = true
      let params = {...this.query}
      getFansList(params).then(res => {
        this.dataList = res.data.records
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    resetQuery () {
      this.query = {
        pageNum: 1,
        pageSize: 10,
        conditions: {}
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          let params = {...this.formModel}
          try {
            if (this.formModel.id) {
              await postUpdateWxFansUser(params)
              this.$message.success('修改成功')
            } else {
              params.idList = this.multipleSelection
              await bindTag(params)
              this.$message.success('成功打上标签')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {}
      this.resetForm("formModel")
    },
  },
}
</script>

<style scoped>
.dh {
  width: 0;
  height: 100px;
  background-color: #1c84c6;
  transition: all 1s;
}
.dh.show {
  width: 200px;
}
.dh.hide {
  width: 0;
}
</style>
